<template>
  <div class="form-item-middleware-container">
    <!-- 单行文本输入 -->
    <el-input v-if="fieldType === 'input'" type="text" v-model="inputValue" v-bind="propConfig" @input="onChange"></el-input>

    <!-- 数字输入 -->
    <el-input v-else-if="fieldType === 'number'" type="number" v-model.trim="inputValue" v-bind="propConfig" @input="onChange"></el-input>

    <!-- 计数器 -->
    <el-input-number v-else-if="fieldType === 'input-number'" v-model="inputValue" v-bind="propConfig" @input="onChange"></el-input-number>

    <!-- 多行文本输入 -->
    <el-input v-else-if="fieldType === 'textarea'" type="textarea" v-model="inputValue" v-bind="propConfig" @input="onChange"></el-input>

    <!-- 单选 -->
    <el-radio-group v-else-if="fieldType === 'radio'" v-model="inputValue" v-bind="propConfig" @change="onChange">
      <el-radio v-for="(item, index) in attributes.options" :key="index" :label="item.value">{{item.label}}</el-radio>
    </el-radio-group>

    <!-- 多选组 -->
    <el-checkbox-group v-else-if="fieldType === 'checkbox-group'" v-model="inputValue" v-bind="propConfig" @change="onChange">
      <el-checkbox v-for="(item, index) in attributes.options" :key="index" :label="item.value">{{item.label}}</el-checkbox>
    </el-checkbox-group>

    <!-- 单个多选 -->
    <el-checkbox v-else-if="fieldType === 'checkbox'" v-model="inputValue" v-bind="propConfig" @change="onChange"></el-checkbox>

    <!-- 下拉选择 -->
    <el-select v-else-if="fieldType === 'select'" v-model="inputValue" @change="onChange" v-bind="propConfig">
      <el-option v-for="(item, index) in attributes.options" :key="index" :value="item.value" :label="item.label"></el-option>
    </el-select>

    <!-- 字典下拉选择 -->
    <base-select-dictionary
      v-else-if="fieldType === 'select-dictionary'"
      v-model="inputValue"
      @change="onChange"
      @selectItem="onDictionarySelectItem"
      v-bind="propConfig"
    ></base-select-dictionary>

    <!-- 日期 -->
    <el-date-picker
      v-else-if="fieldType === 'date'"
      type="date"
      v-model="inputValue"
      value-format="yyyy-MM-dd"
      v-bind="propConfig"
      @change="onChange"
    ></el-date-picker>

    <!-- 日期时间 -->
    <el-date-picker
      v-else-if="fieldType === 'datetime'"
      type="datetime"
      v-model="inputValue"
      value-format="yyyy-MM-dd hh:mm:ss"
      v-bind="propConfig"
      @change="onChange"
    ></el-date-picker>

    <!-- Switch 开关 -->
    <el-switch v-else-if="fieldType === 'switch'" v-model="inputValue" v-bind="propConfig" @change="onChange"></el-switch>

    <!-- 默认文本显示 -->
    <div v-else>
      <span>{{inputValue}}</span>
    </div>
  </div>
</template>

<script>
import _ from 'lodash';

export default {
  name: 'form-item-middleware',
  props: {
    value: null,

    /**
     * 是否禁用状态，如果此处开启，则针对当前表格表单中所有项
     */
    disabled: {
      type: Boolean,
      default: false,
    },

    /**
     * 源数据对象
     */
    dataSource: {
      type: Object,
    },

    /**
     * 字段名称
     */
    fieldName: {
      type: String,
      default: '',
    },

    /**
     * property:
     *    - fieldType 字段类型
     *    - options: 列表
     *    - optionValue: 列表中 value 对应的字段 key, 不设置默认为 value
     *    - optionLabel: 列表中 label 对应的字段 key, 不设置默认为 label
     *    - props: 各表单组件中 props 配置属性[具体配置见 element-ui 对应的表单组件配置]
     *      - placeholder
     *      - disabled
     *      - clearable
     *      ...
     *    - on 监听值变化的回调函数
     *    - onSelectItem 监听选择返回源数据对象的回调函数
     */
    formAttribute: {
      type: Object,
      required: true,
    },
  },

  data() {
    return {
      fieldType: 'text',
      inputValue: null,
      hasError: false,
      attributes: {
        options: [],
        optionValue: 'value',
        optionLabel: 'label',
      },
      propConfig: {},
    };
  },

  watch: {
    value: {
      handler(val) {
        this.inputValue = val;
      },
      immediate: true,
      deep: true,
    },
    disabled: {
      handler(val) {
        if (_.isBoolean(val)) {
          this.propConfig.disabled = val;
        }
      },
      immediate: true,
    },
    formAttribute: {
      handler(attrs) {
        if (_.isObject(attrs)) {
          this.fieldType = attrs.fieldType || 'text';
          Object.keys(this.attributes).forEach(key => {
            if (attrs[key]) {
              this.attributes[key] = attrs[key];
            }
          });
          if (attrs.props) {
            this.propConfig = Object.assign({}, this.propConfig, attrs.props);
          }

          if (!this.propConfig.placeholder) {
            switch (this.fieldType) {
              case 'input':
              case 'textarea':
                this.propConfig.placeholder = '请输入';
                break;
              case 'select-dictionary':
                this.propConfig.block = true;
                break;
              default:
                this.propConfig.placeholder = '请选择';
                break;
            }
          }
        }
      },
      immediate: true,
      deep: true,
    },

    dataSource: {
      handler(val) {
        if (val) {
          const attr = this.formAttribute;
          if (attr.fieldType === 'select-dictionary' && attr.props && !_.isUndefined(attr.props.pid)) {
            if (_.isString(attr.props.pid)) {
              // 绑定动态的 pid 值，用于字段之间的联动
              this.propConfig.pid = val[attr.props.pid];
            } else {
              this.propConfig.pid = attr.props.pid;
            }
          }

          // 获取深层对象路径下的值
          if (this.fieldName.indexOf('.') > -1) {
            this.inputValue = _.get(val, this.fieldName);
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },

  created() {
    // this.initInputValue();
  },

  methods: {
    onChange(val) {
      // 字段类型为 input number 时，由于 element-ui中的 el-input 组件问题，值始终为 string 类型，需要特殊处理
      if (this.fieldType === 'number') {
        this.inputValue = _.toNumber(val);
      } else {
        this.inputValue = val;
      }
      this.$emit('change', this.inputValue, this.dataSource, this.formAttribute);
      if (_.isFunction(this.formAttribute.on)) {
        // this.formAttribute.on(this.inputValue, this.dataSource, this.formAttribute);
        this.formAttribute.on({
          $el: this,
          record: this.inputValue,
          form: this.dataSource,
          column: this.formAttribute,
        });
      }
    },

    /**
     * 下拉字典列表选择回调 - 返回选择的数据对象
     */
    onDictionarySelectItem(record) {
      if (_.isFunction(this.formAttribute.onSelectItem)) {
        // this.formAttribute.onSelectItem(record, this.dataSource, this.formAttribute);
        this.formAttribute.onSelectItem({
          $el: this,
          record,
          form: this.dataSource,
          column: this.formAttribute,
        });
      }
    },

    /**
     * 初始化值
     */
    initInputValue() {
      if (this.formAttribute) {
        switch (this.formAttribute.fieldType) {
          // 当字段类型为 checkbox-group 时，需要手动将 inputValue 的类型设置为 Array 类型，否则选中的值会出错
          case 'checkbox-group':
            this.inputValue = [];
            break;
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.form-item-middleware-container {
  width: 100%;
  height: 100%;

  .el-input, .el-select {
    width: 100%;

    /deep/ .el-input__inner {
      max-width: 100%;
    }
  }
}
</style>

